package com.cdc.image;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class DownFile {
    private static final String  TAG="DownFile";
    private String urlStr;

    public DownFile(String urlStr) {
        this.urlStr = urlStr;
    }

    public File getImageFile(){
        File fileDir=new File(Environment.getExternalStorageDirectory().getAbsolutePath()+File.separatorChar+Environment.DIRECTORY_DOWNLOADS);
        File file=null;
        if(fileDir.exists() && fileDir.isDirectory()){
            String  ss=UUID.nameUUIDFromBytes(urlStr.getBytes()).toString();
            HttpURLConnection httpURLConnection=null;
            InputStream inputStream=null;
            BufferedInputStream bis=null;
            try {
                URL url=new URL(urlStr);
                httpURLConnection= (HttpURLConnection) url.openConnection();
                String type=httpURLConnection.getContentType();
                String length=httpURLConnection.getContentLength()+"";
                //返回:/123.jpg
                String urlFilePath = httpURLConnection.getURL().getFile();
                //返回:.jpg
                String fileName = urlFilePath.substring(urlFilePath.lastIndexOf("."));
                file=new File(fileDir,ss+fileName);
                printHeaders(httpURLConnection);
                inputStream=httpURLConnection.getInputStream();
                bis=new BufferedInputStream(inputStream);
                writeFile(file,bis);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if(httpURLConnection!=null){
                    httpURLConnection.disconnect();
                }
                    try {
                        //关闭打开的流对象
                        if(inputStream!=null){
                            inputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }else{
            Log.e("123","目录不存在 跳出");
        }

        return file;
    }

    /**
     * 打印请求头
     * @param httpURLConnection
     */
    private void printHeaders(HttpURLConnection httpURLConnection) {
        Map<String,List<String>> maps= httpURLConnection.getHeaderFields();
        for (Map.Entry<String, List<String>> stringListEntry : maps.entrySet()) {
            List<String>  values=stringListEntry.getValue();
            for (String value : values) {
                Log.i(TAG,"key="+stringListEntry.getKey()+",value="+value);
            }
        }
    }

    public Bitmap getBitmap(){
        Bitmap bitmap=null;
        HttpURLConnection httpURLConnection=null;
        InputStream inputStream=null;
        BufferedInputStream bis=null;
        try {
            URL url=new URL(urlStr);
            httpURLConnection= (HttpURLConnection) url.openConnection();
            String type=httpURLConnection.getContentType();
            String length=httpURLConnection.getContentLength()+"";
            Log.i(TAG,"type="+type+",length="+length);
           printHeaders(httpURLConnection);
            inputStream=httpURLConnection.getInputStream();
            bis=new BufferedInputStream(inputStream);
            bitmap= BitmapFactory.decodeStream(bis);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(httpURLConnection!=null){
                httpURLConnection.disconnect();
            }
            if(inputStream!=null){
                try {
                    if(bis!=null  && inputStream!=null){
                        bis.close();
                        inputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bitmap;
    }

    /**
     * 将从网络获取的输入流写入到文件中
     * @param file
     * @param bufferedInputStream
     */
    private void writeFile(File file,BufferedInputStream bufferedInputStream){
        OutputStream outputStream=null;
        try {
            outputStream=new FileOutputStream(file);
            byte[] b=new byte[1024];
            int len=0;
            while( (len=bufferedInputStream.read(b)) !=-1){  //先读到内存
                outputStream.write(b, 0, len);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outputStream.close();
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
